<template>
  <div>
    <el-row type="flex" justify="center" align="middle" class="loginWrapper">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="clearInput">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 11,
            message: "长度在 5 到 11 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    onSubmit() {
      if (!this.form.username || !this.form.password) {
        this.$message.error("请输入完整信息");
        return;
      }
      this.$axios({
        url: "/login",
        method: "POST",
        data: this.form,
      }).then((res) => {
        console.log(res);
        const { message, data } = res.data;
        // 登录成功后把数据保存到本地
        localStorage.setItem("token", data.token);
        localStorage.setItem("user", JSON.stringify(data.user));
        this.$message.success(message);
        // 跳转到首页
        this.$router.push("/");
      });
    },
    // 重置表单
    clearInput() {
      this.form.username = "";
      this.form.password = "";
    },
  },
};
</script>

<style lang="less" scoped>
.loginWrapper {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}
</style>
